#!/bin/bash

# 服务器诊断脚本
echo "======================================"
echo "    服务器诊断报告"
echo "======================================"

# 1. 查找所有Node.js相关文件
echo "1. 查找Node.js文件..."
echo "查找start-server.js:"
find / -name "start-server.js" 2>/dev/null
echo
echo "查找app.js:"
find / -name "app.js" 2>/dev/null | head -5
echo
echo "查找package.json:"
find / -name "package.json" 2>/dev/null | head -5
echo

# 2. 检查当前目录内容
echo "2. 当前目录内容:"
ls -la /root/
echo

# 3. 检查环境变量文件
echo "3. 检查.env文件:"
if [ -f "/root/.env.production" ]; then
    echo "✓ .env.production存在:"
    cat /root/.env.production
else
    echo "❌ .env.production不存在"
fi
echo

# 4. 检查Node.js环境
echo "4. Node.js环境:"
which node
node --version 2>/dev/null || echo "Node.js未安装或不可用"
which npm
npm --version 2>/dev/null || echo "npm未安装或不可用"
echo

# 5. 检查进程
echo "5. 当前Node.js进程:"
ps aux | grep node | grep -v grep
echo

# 6. 检查端口
echo "6. 端口使用情况:"
netstat -tlnp | grep -E ':(80|8080|3000|5000)'
echo

# 7. 检查防火墙
echo "7. 防火墙状态:"
if command -v ufw >/dev/null 2>&1; then
    ufw status
elif command -v firewall-cmd >/dev/null 2>&1; then
    firewall-cmd --list-all
else
    echo "未找到防火墙管理工具"
fi
echo

# 8. 检查系统资源
echo "8. 系统资源:"
echo "内存使用:"
free -h
echo "磁盘使用:"
df -h /
echo

# 9. 检查日志
echo "9. 检查日志文件:"
if [ -f "/var/log/backend.log" ]; then
    echo "✓ 后端日志存在:"
    tail -10 /var/log/backend.log
else
    echo "❌ 后端日志不存在"
fi
echo

# 10. 网络连接测试
echo "10. 网络连接测试:"
echo "测试本地8080端口:"
curl -s -m 3 http://localhost:8080/health || echo "本地8080端口无响应"
echo "测试本地80端口:"
curl -s -m 3 http://localhost:80/ || echo "本地80端口无响应"
echo

echo "======================================"
echo "诊断完成！请查看上述信息找出问题"
echo "======================================"